<template>
  <div class="photo-editor" v-if="photo">
    <div class="editor-header">
      <div class="editor-title">编辑照片</div>
      <div class="editor-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave" :disabled="!hasChanges">保存</el-button>
      </div>
    </div>
    
    <div class="editor-content">
      <div class="editor-canvas">
        <div class="canvas-container" ref="canvasContainer">
          <canvas ref="canvas" :width="canvasWidth" :height="canvasHeight"></canvas>
          <div class="canvas-loading" v-if="imageLoading">
            <el-icon class="is-loading"><Loading /></el-icon>
          </div>
        </div>
      </div>
      
      <div class="editor-controls">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="调整" name="adjust">
            <div class="control-section">
              <div class="control-item">
                <div class="control-label">亮度</div>
                <el-slider 
                  v-model="adjustments.brightness" 
                  :min="-100" 
                  :max="100" 
                  :step="1"
                  @input="applyAdjustments"
                />
                <div class="control-value">{{ adjustments.brightness }}</div>
              </div>
              
              <div class="control-item">
                <div class="control-label">对比度</div>
                <el-slider 
                  v-model="adjustments.contrast" 
                  :min="-100" 
                  :max="100" 
                  :step="1"
                  @input="applyAdjustments"
                />
                <div class="control-value">{{ adjustments.contrast }}</div>
              </div>
              
              <div class="control-item">
                <div class="control-label">饱和度</div>
                <el-slider 
                  v-model="adjustments.saturation" 
                  :min="-100" 
                  :max="100" 
                  :step="1"
                  @input="applyAdjustments"
                />
                <div class="control-value">{{ adjustments.saturation }}</div>
              </div>
              
              <div class="control-item">
                <div class="control-label">色相</div>
                <el-slider 
                  v-model="adjustments.hue" 
                  :min="-180" 
                  :max="180" 
                  :step="1"
                  @input="applyAdjustments"
                />
                <div class="control-value">{{ adjustments.hue }}</div>
              </div>
              
              <div class="control-item">
                <div class="control-label">模糊</div>
                <el-slider 
                  v-model="adjustments.blur" 
                  :min="0" 
                  :max="10" 
                  :step="0.1"
                  @input="applyAdjustments"
                />
                <div class="control-value">{{ adjustments.blur }}</div>
              </div>
              
              <div class="control-item">
                <div class="control-label">锐化</div>
                <el-slider 
                  v-model="adjustments.sharpen" 
                  :min="0" 
                  :max="10" 
                  :step="0.1"
                  @input="applyAdjustments"
                />
                <div class="control-value">{{ adjustments.sharpen }}</div>
              </div>
              
              <div class="control-actions">
                <el-button size="small" @click="resetAdjustments">重置</el-button>
                <el-button size="small" @click="autoAdjust">自动调整</el-button>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="变换" name="transform">
            <div class="control-section">
              <div class="control-item">
                <div class="control-label">旋转</div>
                <div class="button-group">
                  <el-button size="small" @click="rotate(-90)">
                    <el-icon><RefreshLeft /></el-icon>
                    左转90°
                  </el-button>
                  <el-button size="small" @click="rotate(90)">
                    <el-icon><RefreshRight /></el-icon>
                    右转90°
                  </el-button>
                  <el-button size="small" @click="rotate(180)">
                    <el-icon><Refresh /></el-icon>
                    旋转180°
                  </el-button>
                </div>
              </div>
              
              <div class="control-item">
                <div class="control-label">翻转</div>
                <div class="button-group">
                  <el-button size="small" @click="flip('horizontal')">
                    <el-icon><Sort /></el-icon>
                    水平翻转
                  </el-button>
                  <el-button size="small" @click="flip('vertical')">
                    <el-icon><Sort /></el-icon>
                    垂直翻转
                  </el-button>
                </div>
              </div>
              
              <div class="control-item">
                <div class="control-label">裁剪</div>
                <div class="button-group">
                  <el-button size="small" @click="startCrop">
                    <el-icon><Crop /></el-icon>
                    开始裁剪
                  </el-button>
                  <el-button size="small" @click="cancelCrop" v-if="cropping">
                    取消裁剪
                  </el-button>
                  <el-button size="small" @click="applyCrop" v-if="cropping">
                    应用裁剪
                  </el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="滤镜" name="filter">
            <div class="filter-grid">
              <div 
                v-for="filter in filters" 
                :key="filter.name"
                class="filter-item"
                :class="{ 'filter-active': currentFilter === filter.name }"
                @click="applyFilter(filter.name)"
              >
                <div class="filter-preview">
                  <canvas :ref="`filter-preview-${filter.name}`" width="100" height="100"></canvas>
                </div>
                <div class="filter-name">{{ filter.label }}</div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
  <div v-else class="photo-editor-empty">
    <el-empty description="未选择照片" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { ElButton, ElIcon, ElTabs, ElTabPane, ElSlider, ElEmpty, ElMessage } from 'element-plus';
import { 
  Loading, 
  RefreshLeft, 
  RefreshRight, 
  Refresh, 
  Sort, 
  Crop 
} from '@element-plus/icons-vue';
import type { Photo } from '@/types';

interface Props {
  photo: Photo | null;
}

interface Emits {
  (e: 'cancel'): void;
  (e: 'save', photo: Photo): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 当前激活的标签页
const activeTab = ref('adjust');
// 图片加载状态
const imageLoading = ref(true);
// 画布引用
const canvas = ref<HTMLCanvasElement | null>(null);
const canvasContainer = ref<HTMLDivElement | null>(null);
// 画布尺寸
const canvasWidth = ref(800);
const canvasHeight = ref(600);
// 原始图片
const originalImage = ref<HTMLImageElement | null>(null);
// 当前图片数据
const currentImageData = ref<ImageData | null>(null);
// 调整参数
const adjustments = ref({
  brightness: 0,
  contrast: 0,
  saturation: 0,
  hue: 0,
  blur: 0,
  sharpen: 0
});
// 初始调整参数（用于重置）
const initialAdjustments = { ...adjustments.value };
// 旋转角度
const rotation = ref(0);
// 翻转状态
const flipState = ref({
  horizontal: false,
  vertical: false
});
// 裁剪状态
const cropping = ref(false);
const cropArea = ref({
  x: 0,
  y: 0,
  width: 0,
  height: 0
});
// 当前滤镜
const currentFilter = ref('none');

// 滤镜定义
const filters = [
  { name: 'none', label: '无滤镜' },
  { name: 'grayscale', label: '黑白' },
  { name: 'sepia', label: '复古' },
  { name: 'vintage', label: '怀旧' },
  { name: 'cold', label: '冷色调' },
  { name: 'warm', label: '暖色调' },
  { name: 'dramatic', label: '戏剧' },
  { name: 'vivid', label: '鲜艳' }
];

// 是否有更改
const hasChanges = computed(() => {
  return (
    adjustments.value.brightness !== initialAdjustments.brightness ||
    adjustments.value.contrast !== initialAdjustments.contrast ||
    adjustments.value.saturation !== initialAdjustments.saturation ||
    adjustments.value.hue !== initialAdjustments.hue ||
    adjustments.value.blur !== initialAdjustments.blur ||
    adjustments.value.sharpen !== initialAdjustments.sharpen ||
    rotation.value !== 0 ||
    flipState.value.horizontal !== false ||
    flipState.value.vertical !== false ||
    currentFilter.value !== 'none'
  );
});

// 监听photo变化
watch(() => props.photo, (newPhoto) => {
  if (newPhoto) {
    loadImage(newPhoto.filePath);
  } else {
    resetEditor();
  }
}, { immediate: true });

// 加载图片
const loadImage = (imagePath: string) => {
  imageLoading.value = true;
  
  const img = new Image();
  img.onload = () => {
    originalImage.value = img;
    
    // 调整画布尺寸以适应图片
    const maxWidth = canvasContainer.value?.clientWidth || 800;
    const maxHeight = window.innerHeight - 300;
    
    let width = img.width;
    let height = img.height;
    
    if (width > maxWidth) {
      height = (maxWidth / width) * height;
      width = maxWidth;
    }
    
    if (height > maxHeight) {
      width = (maxHeight / height) * width;
      height = maxHeight;
    }
    
    canvasWidth.value = width;
    canvasHeight.value = height;
    
    nextTick(() => {
      if (canvas.value) {
        const ctx = canvas.value.getContext('2d');
        if (ctx) {
          canvas.value.width = width;
          canvas.value.height = height;
          ctx.drawImage(img, 0, 0, width, height);
          currentImageData.value = ctx.getImageData(0, 0, width, height);
          imageLoading.value = false;
          
          // 生成滤镜预览
          generateFilterPreviews();
        }
      }
    });
  };
  
  img.onerror = () => {
    imageLoading.value = false;
    ElMessage.error('图片加载失败');
  };
  
  img.src = `file://${imagePath}`;
};

// 应用调整
const applyAdjustments = () => {
  if (!canvas.value || !originalImage.value) return;
  
  const ctx = canvas.value.getContext('2d');
  if (!ctx) return;
  
  // 清除画布
  ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  
  // 应用CSS滤镜
  const filters = [];
  
  if (adjustments.value.brightness !== 0) {
    filters.push(`brightness(${100 + adjustments.value.brightness}%)`);
  }
  
  if (adjustments.value.contrast !== 0) {
    filters.push(`contrast(${100 + adjustments.value.contrast}%)`);
  }
  
  if (adjustments.value.saturation !== 0) {
    filters.push(`saturate(${100 + adjustments.value.saturation}%)`);
  }
  
  if (adjustments.value.hue !== 0) {
    filters.push(`hue-rotate(${adjustments.value.hue}deg)`);
  }
  
  if (adjustments.value.blur > 0) {
    filters.push(`blur(${adjustments.value.blur}px)`);
  }
  
  if (adjustments.value.sharpen > 0) {
    // 锐化需要使用Canvas滤镜或自定义算法
    // 这里简化处理
  }
  
  // 应用变换
  ctx.save();
  
  // 应用旋转
  if (rotation.value !== 0) {
    ctx.translate(canvasWidth.value / 2, canvasHeight.value / 2);
    ctx.rotate((rotation.value * Math.PI) / 180);
    ctx.translate(-canvasWidth.value / 2, -canvasHeight.value / 2);
  }
  
  // 应用翻转
  if (flipState.value.horizontal || flipState.value.vertical) {
    ctx.translate(
      flipState.value.horizontal ? canvasWidth.value : 0,
      flipState.value.vertical ? canvasHeight.value : 0
    );
    ctx.scale(
      flipState.value.horizontal ? -1 : 1,
      flipState.value.vertical ? -1 : 1
    );
  }
  
  // 应用滤镜
  ctx.filter = filters.join(' ');
  
  // 绘制图片
  ctx.drawImage(
    originalImage.value,
    0, 0,
    canvasWidth.value,
    canvasHeight.value
  );
  
  ctx.restore();
  
  // 保存当前图像数据
  currentImageData.value = ctx.getImageData(0, 0, canvasWidth.value, canvasHeight.value);
};

// 重置调整
const resetAdjustments = () => {
  adjustments.value = { ...initialAdjustments };
  rotation.value = 0;
  flipState.value = { horizontal: false, vertical: false };
  currentFilter.value = 'none';
  applyAdjustments();
};

// 自动调整
const autoAdjust = () => {
  // 这里可以实现自动调整算法
  // 简化处理，重置所有调整
  resetAdjustments();
  ElMessage.info('自动调整功能待实现');
};

// 旋转
const rotate = (degrees: number) => {
  rotation.value = (rotation.value + degrees) % 360;
  applyAdjustments();
};

// 翻转
const flip = (direction: 'horizontal' | 'vertical') => {
  flipState.value[direction] = !flipState.value[direction];
  applyAdjustments();
};

// 开始裁剪
const startCrop = () => {
  cropping.value = true;
  // 初始化裁剪区域为整个图片
  cropArea.value = {
    x: 0,
    y: 0,
    width: canvasWidth.value,
    height: canvasHeight.value
  };
  
  // 这里应该添加裁剪框的交互逻辑
  ElMessage.info('裁剪功能待实现');
};

// 取消裁剪
const cancelCrop = () => {
  cropping.value = false;
  applyAdjustments();
};

// 应用裁剪
const applyCrop = () => {
  if (!canvas.value || !currentImageData.value) return;
  
  const ctx = canvas.value.getContext('2d');
  if (!ctx) return;
  
  // 创建临时画布存储裁剪结果
  const tempCanvas = document.createElement('canvas');
  const tempCtx = tempCanvas.getContext('2d');
  if (!tempCtx) return;
  
  tempCanvas.width = cropArea.value.width;
  tempCanvas.height = cropArea.value.height;
  
  // 复制裁剪区域
  tempCtx.putImageData(
    currentImageData.value,
    0, 0,
    cropArea.value.x,
    cropArea.value.y,
    cropArea.value.width,
    cropArea.value.height
  );
  
  // 调整主画布尺寸
  canvasWidth.value = cropArea.value.width;
  canvasHeight.value = cropArea.value.height;
  canvas.value.width = canvasWidth.value;
  canvas.value.height = canvasHeight.value;
  
  // 绘制裁剪结果
  ctx.drawImage(tempCanvas, 0, 0);
  
  // 更新当前图像数据
  currentImageData.value = ctx.getImageData(0, 0, canvasWidth.value, canvasHeight.value);
  
  // 重置裁剪状态
  cropping.value = false;
};

// 应用滤镜
const applyFilter = (filterName: string) => {
  currentFilter.value = filterName;
  
  if (!canvas.value || !originalImage.value) return;
  
  const ctx = canvas.value.getContext('2d');
  if (!ctx) return;
  
  // 清除画布
  ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  
  // 应用滤镜
  ctx.filter = getFilterCSS(filterName);
  
  // 绘制图片
  ctx.drawImage(
    originalImage.value,
    0, 0,
    canvasWidth.value,
    canvasHeight.value
  );
  
  // 保存当前图像数据
  currentImageData.value = ctx.getImageData(0, 0, canvasWidth.value, canvasHeight.value);
};

// 获取滤镜CSS
const getFilterCSS = (filterName: string): string => {
  switch (filterName) {
    case 'grayscale':
      return 'grayscale(100%)';
    case 'sepia':
      return 'sepia(100%)';
    case 'vintage':
      return 'sepia(50%) contrast(120%) brightness(90%)';
    case 'cold':
      return 'hue-rotate(180deg) saturate(140%)';
    case 'warm':
      return 'hue-rotate(-30deg) saturate(140%) brightness(110%)';
    case 'dramatic':
      return 'contrast(150%) brightness(90%) saturate(120%)';
    case 'vivid':
      return 'saturate(200%) contrast(120%)';
    default:
      return 'none';
  }
};

// 生成滤镜预览
const generateFilterPreviews = () => {
  if (!originalImage.value) return;
  
  filters.forEach(filter => {
    nextTick(() => {
      const previewCanvas = document.querySelector(`[ref="filter-preview-${filter.name}"]`) as HTMLCanvasElement;
      if (!previewCanvas) return;
      
      const ctx = previewCanvas.getContext('2d');
      if (!ctx) return;
      
      // 应用滤镜
      ctx.filter = getFilterCSS(filter.name);
      
      // 绘制缩略图
      ctx.drawImage(
        originalImage.value!,
        0, 0,
        100, 100
      );
    });
  });
};

// 重置编辑器
const resetEditor = () => {
  adjustments.value = { ...initialAdjustments };
  rotation.value = 0;
  flipState.value = { horizontal: false, vertical: false };
  currentFilter.value = 'none';
  cropping.value = false;
  originalImage.value = null;
  currentImageData.value = null;
  imageLoading.value = true;
};

// 处理取消
const handleCancel = () => {
  resetEditor();
  emit('cancel');
};

// 处理保存
const handleSave = async () => {
  if (!canvas.value || !props.photo) return;
  
  try {
    // 将画布内容转换为Blob
    canvas.value.toBlob(async (blob) => {
      if (!blob) {
        ElMessage.error('保存失败');
        return;
      }
      
      // 这里应该将编辑后的图片保存到文件系统
      // 并更新数据库中的照片记录
      ElMessage.success('照片已保存');
      emit('save', props.photo);
    }, 'image/jpeg', 0.95);
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 组件挂载后初始化
onMounted(() => {
  // 初始化画布尺寸
  if (canvasContainer.value) {
    canvasWidth.value = canvasContainer.value.clientWidth;
    canvasHeight.value = 600;
  }
});
</script>

<style scoped lang="scss">
.photo-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    .editor-title {
      font-size: 18px;
      font-weight: 500;
      color: var(--el-text-color-primary);
    }
    
    .editor-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .editor-content {
    display: flex;
    flex: 1;
    overflow: hidden;
    
    .editor-canvas {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: var(--el-fill-color-lighter);
      position: relative;
      
      .canvas-container {
        position: relative;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        
        canvas {
          display: block;
          background-color: white;
        }
        
        .canvas-loading {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: rgba(255, 255, 255, 0.7);
          
          .el-icon {
            font-size: 24px;
            color: var(--el-color-primary);
          }
        }
      }
    }
    
    .editor-controls {
      width: 300px;
      border-left: 1px solid var(--el-border-color-light);
      overflow: hidden;
      display: flex;
      flex-direction: column;
      
      .el-tabs {
        height: 100%;
        display: flex;
        flex-direction: column;
        
        :deep(.el-tabs__content) {
          flex: 1;
          overflow-y: auto;
        }
      }
      
      .control-section {
        padding: 16px;
        
        .control-item {
          margin-bottom: 20px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .control-label {
            font-size: 14px;
            color: var(--el-text-color-primary);
            margin-bottom: 8px;
          }
          
          .control-value {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            text-align: center;
            margin-top: 4px;
          }
          
          .button-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            
            .el-button {
              flex: 1;
              min-width: 100px;
            }
          }
        }
        
        .control-actions {
          display: flex;
          gap: 8px;
          margin-top: 16px;
          
          .el-button {
            flex: 1;
          }
        }
      }
      
      .filter-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
        padding: 16px;
        
        .filter-item {
          cursor: pointer;
          border-radius: 8px;
          overflow: hidden;
          border: 2px solid transparent;
          transition: all 0.2s ease;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
          }
          
          &.filter-active {
            border-color: var(--el-color-primary);
          }
          
          .filter-preview {
            height: 100px;
            overflow: hidden;
            
            canvas {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
          
          .filter-name {
            padding: 8px;
            text-align: center;
            font-size: 12px;
            color: var(--el-text-color-primary);
            background-color: var(--el-fill-color-light);
          }
        }
      }
    }
  }
}

.photo-editor-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

// 响应式设计
@media (max-width: 768px) {
  .photo-editor {
    .editor-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
    
    .editor-content {
      flex-direction: column;
      
      .editor-canvas {
        height: 300px;
      }
      
      .editor-controls {
        width: 100%;
        border-left: none;
        border-top: 1px solid var(--el-border-color-light);
      }
    }
  }
}
</style>